package com.example.feidaolumanager.pages.ui.machine

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.feidaolumanager.Constants
import com.example.feidaolumanager.LoginActivity
import com.example.feidaolumanager.R
import com.example.feidaolumanager.componant.DropdownSelectLevel3Area
import com.example.feidaolumanager.databinding.FragmentMachinesBinding
import com.example.feidaolumanager.pages.AddMachineActivity
import com.example.feidaolumanager.pages.MachineDetailActivity
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.viewModel.AreasViewModel
import com.example.feidaolumanager.viewModel.MainViewModel

class MachinesFragment : Fragment() {

    private var _binding: FragmentMachinesBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private var selectedAreaKey = -1


    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        val machinesViewModel = ViewModelProvider(requireActivity())[MachinesViewModel::class.java]
        val areasViewModel = ViewModelProvider(requireActivity())[AreasViewModel::class.java]

        _binding = FragmentMachinesBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val composeView: ComposeView = binding.tvCompose

        val user: User? = activity?.intent?.getSerializableExtra("user") as User?

        if (user != null) {
            machinesViewModel.getMachines(user)
        } else {
            Log.e(this.toString(), "onCreateView: 用户信息异常的为空")
        }

        machinesViewModel.deleteMachineResult.observe(viewLifecycleOwner) {
            if (it != null) {
                if (it.code == Constants.success_code) {
                    Toast.makeText(activity, "删除成功", Toast.LENGTH_LONG).show()
                    // 能到删除这一步，用户应该不为空
                    machinesViewModel.getMachines(user!!, selectedAreaKey, 3)
                } else {
                    Toast.makeText(activity, "删除失败:${it.msg}", Toast.LENGTH_LONG).show()
                }
            }
        }

        machinesViewModel.tokenExpire.observe(viewLifecycleOwner) {
            if (it) {
                Toast.makeText(context, "登录过期，请重新登录", Toast.LENGTH_LONG).show()
                // 删除token
                val preferences = requireActivity().getSharedPreferences(
                    Constants.store_key,
                    Context.MODE_PRIVATE
                )
                with(preferences.edit()) {
                    remove("user")
                    clear()
                    apply()
                }
                startActivity(
                    Intent(
                        context, LoginActivity::class.java
                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                )
                this.activity?.finish()
            }
        }

        val forActivityResult =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                // 从别的界面回来的刷新数据
                if (selectedAreaKey != -1) {
                    machinesViewModel.getMachines(user!!, selectedAreaKey, 3)
                } else {
                    machinesViewModel.getMachines(user!!)
                }
            }

        composeView.setContent {
            // 下拉选择工地
            // 显示设备列表
            val lazyListState = rememberLazyListState()


            Scaffold(topBar = {
                TopAppBar(title = {
                    Text("电子标签管理", color = Color.White)
                },
                    modifier = Modifier.background(color = Color.DarkGray),
                    colors = TopAppBarDefaults.smallTopAppBarColors(
                        containerColor = Color(
                            0, 172, 98
                        )
                    ),
                    actions = {
                        if ((user?.level ?: 0) == 4) {
                            Icon(imageVector = Icons.Default.Add,
                                tint = Color.White,
                                contentDescription = "添加设备按钮",
                                modifier = Modifier
                                    .clickable {
                                        // 添加跳转到添加设备界面
                                        forActivityResult.launch(
                                            Intent(
                                                activity, AddMachineActivity::class.java
                                            ).putExtra("user", user)
                                        )
                                    }
                                    .size(50.dp))
                        }
                    })
            }) {

                var ifShowDeleteMachineDialog by remember {
                    mutableStateOf(false)
                }
                val currentDeleteMachinesId by remember {
                    mutableIntStateOf(-1)
                }

                Column(
                    modifier = Modifier.padding(it),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {


                    if (ifShowDeleteMachineDialog) {
                        AlertDialog(onDismissRequest = {
                            ifShowDeleteMachineDialog = false
                        }, confirmButton = {
                            TextButton(onClick = {
                                ifShowDeleteMachineDialog = false
                                machinesViewModel.deleteMachine(
                                    currentDeleteMachinesId
                                )
                            }) {
                                Text(text = "删除")
                            }
                        }, dismissButton = {
                            TextButton(onClick = {
                                ifShowDeleteMachineDialog = false
                            }) {
                                Text(text = "取消")
                            }
                        }, title = {
                            Text(text = "是否确认删除这台机器$currentDeleteMachinesId")
                        })
                    }

                    if (user != null) {
                        DropdownSelectLevel3Area(
                            user = user,
                            areasViewModel = areasViewModel
                        ) { areaKey ->
                            selectedAreaKey = areaKey
                            machinesViewModel.getMachines(user, selKey = areaKey, 3)
                        }
                    }

                    Spacer(modifier = Modifier.height(10.dp))

                    LazyColumn(
                        state = lazyListState, horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        items(machinesViewModel.machineList.value) { machineItem ->
                            Box(modifier = Modifier
                                .border(color = Color.Black, width = 1.dp)
                                .height(210.dp)
                                .width(300.dp)
                                .clickable {
                                    forActivityResult.launch(
                                        Intent(
                                            context, MachineDetailActivity::class.java
                                        )
                                            .putExtra("machine", machineItem)
                                            .putExtra("user", user)
                                    )
                                }) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.Center,
                                    modifier = Modifier.align(Alignment.Center)
                                ) {
                                    Text(text = machineItem.mec_no ?: "")

                                    val value = machineItem.electric?.toInt()
                                    var electricTextColor: Color = Color.Green

                                    if (value != null) {
                                        electricTextColor = if (value >= 80) {
                                            Color.Green
                                        } else if (value >= 50) {
                                            Color.Yellow
                                        } else if (value >= 30) {
                                            Color(250, 150, 0)
                                        } else {
                                            Color.Red
                                        }
                                    }

                                    var id = R.drawable.excavator
                                    when (machineItem.type_id) {
                                        4 -> {
                                            id = R.drawable.excavator
                                        }

                                        30 -> {
                                            id = R.drawable.loader
                                        }

                                        31 -> {
                                            id = R.drawable.crane
                                        }

                                        32 -> {
                                            id = R.drawable.forklift
                                        }

                                        else -> {}
                                    }
                                    Image(
                                        modifier = Modifier
                                            .height(100.dp)
                                            .width(150.dp),
                                        painter = painterResource(id = id),
                                        contentDescription = "机械图片",
                                    )

                                    if (machineItem.electric == null) {
                                        Text(text = "")
                                    } else {
                                        Text(
                                            text = "电量: ${machineItem.electric}%",
                                            color = electricTextColor
                                        )
                                    }

                                    when (machineItem.status) {
                                        0 -> {
                                            Text(text = "静止", color = Color.Gray)
                                        }

                                        1 -> {
                                            Text(text = "运动", color = Color.Green)
                                        }

                                        else -> {
                                            Text(text = "离线", color = Color.Yellow)
                                        }
                                    }
                                    Log.i(this@MachinesFragment.toString(), machineItem.title ?: "")

                                }

                            }
                            Spacer(modifier = Modifier.height(10.dp))
                        }
                    }
                }


            }


        }
        return root
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDetach() {
        super.onDetach()
        ViewModelProvider(requireActivity()).get(MainViewModel::class.java).ifShowMenu.value = true
    }
}